package com.ysxsoft.wdg.ui.activity.home;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.classic.common.MultipleStatusView;
import com.kepler.jd.Listener.OpenAppAction;
import com.kepler.jd.login.KeplerApiManager;
import com.kepler.jd.sdk.bean.KeplerAttachParameter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.socks.library.KLog;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.home.JxGoodsAdapter;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.response.HomeProductResponse;
import com.ysxsoft.wdg.bean.response.JDConvertResponse;
import com.ysxsoft.wdg.bean.response.JDResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.login.LoginValid;
import com.ysxsoft.wdg.util.AlibcUtils;
import com.ysxsoft.wdg.util.BigDecimalUtil;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.delayaction.Action;
import com.ysxsoft.wdg.util.delayaction.SingleCall;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 淘宝客搜索结果
 */
public class JDSearchListActivity extends BaseActivity {

    public static void start(Context context, String keyword) {
        Intent intent = new Intent(context, JDSearchListActivity.class);
        intent.putExtra("keyword", keyword);
        context.startActivity(intent);
    }

    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    EditText titleContent;
    @BindView(R.id.tv0)
    TextView tv0;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.tv2)
    TextView tv2;
    @BindView(R.id.tv3)
    TextView tv3;
    @BindView(R.id.iv3)
    ImageView iv3;
    @BindView(R.id.recyclerview2)
    RecyclerView recyclerview2;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;

    private TextView[] textViews;

    private JxGoodsAdapter adapter;
    private String keyword;
    private int page=1;
    private int type=0;//综合0，销量1，最新2，到手价倒序3， 到手价正序4

    @Override
    protected int getLayoutId() {
        return R.layout.activity_jd_search_list;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        titleContent.setText("");

        keyword=getIntent().getStringExtra("keyword");
        textViews = new TextView[]{tv0, tv1, tv2, tv3};

        recyclerview2.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        adapter = new JxGoodsAdapter(R.layout.item_goods);
        recyclerview2.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SingleCall.getInstance().addAction(new Action() {
                    @Override
                    public void call() {
                        JDResponse.DataBean item = (JDResponse.DataBean) adapter.getItem(position);
                        convertUrl(item.getDiscount_link(), item.getGoods_id());
                    }
                }).addValid(new LoginValid(mContext, 1)).doCall();
            }
        });

        setSelect(0);
    }

    @Override
    protected void setListener() {
            refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    page = 1;
                    getProductList();
                }
            });
            refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
                @Override
                public void onLoadmore(RefreshLayout refreshlayout) {
                    page++;
                    getProductList();
                }
            });
    }

    @OnClick({R.id.title_finish, R.id.tv0, R.id.tv1, R.id.tv2, R.id.tv3,R.id.title_tv_r})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.tv0:
                type = 0;
                setSelect(0);
                break;
            case R.id.tv1:
                type = 1;
                setSelect(1);
                break;
            case R.id.tv2:
                type = 2;
                setSelect(2);
                break;
            case R.id.tv3:
                type = (type == 3) ? 4 : 3;
                setSelect(3);
                iv3.setImageResource((type == 3) ? R.mipmap.xu_down : R.mipmap.xu_up);
                break;
            case R.id.title_tv_r:
                page=1;
                getProductList();
                break;
        }
    }

    private void setSelect(int position) {
        for (int i = 0; i < textViews.length; i++) {
            textViews[i].setSelected(i == position);
        }
        page=1;
        getProductList();
    }

    /**
     * 获取京东数据
     */
    private void getProductList() {
        if (page == 1) {
            multStatusView.showLoading();
        }
        OkHttpUtils.post()
                .url(UrlHost.JD_LIST)
                .addParams("page", page + "")
                .addParams("uid",SharePrefUtils.getUserId())
                .addParams("keyword",keyword)
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    multStatusView.showError();
                    reset();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                reset();
                if (response != null) {
                    JDResponse bean = JsonUtils.parseByGson(response, JDResponse.class);
                    if (bean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(bean.getCode())) {
                        List<JDResponse.DataBean> list = bean.getData();
                        if (page == 1) {
                            multStatusView.showContent();
                            if (list != null && !list.isEmpty()) {
                                adapter.setNewData(list);
                            } else {
                                multStatusView.showEmpty();
                            }
                        } else {
                            if(list!=null){
                                adapter.addData(list);
                            }
                        }
                    }
                } else {
                    multStatusView.showError();
                }
            }
        });
    }

    private void reset() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh(true);
        }
        refreshLayout.finishLoadmore();
    }

    class JxGoodsAdapter extends BaseQuickAdapter<JDResponse.DataBean, BaseViewHolder> {
        public JxGoodsAdapter(int layoutResId) {
            super(layoutResId);
        }

        public void clear() {
            getData().clear();
            notifyDataSetChanged();
        }

        @Override
        protected void convert(BaseViewHolder helper, JDResponse.DataBean item) {
            TextView tvOldPrice2 = helper.getView(R.id.tv_old_money2);//隐藏到手价上边的旧价格
            tvOldPrice2.setVisibility(View.GONE);

            String oldP = item.getGoods_price();

            String discount = item.getDiscount_price();//最终价格
            helper.setText(R.id.tv_name, item.getGoods_name());
            TextView tvOldPrice = helper.getView(R.id.tv_old_money);
            ViewUtils.setDeletLine(tvOldPrice);
            tvOldPrice.setText(mContext.getString(R.string.price_rmb, oldP));//旧价格
            String sub = BigDecimalUtil.formatDoubleScale(BigDecimalUtil.sub(Double.parseDouble(oldP), Double.parseDouble(discount)));
            helper.setText(R.id.tv_money, mContext.getString(R.string.price_rmb, sub));//到手价格

            helper.setText(R.id.tv_quan, mContext.getString(R.string.price_rmb, discount) + "元优惠");//优惠券
            helper.setText(R.id.tv_sold, "赚¥" + item.getZhuan());//赚的钱数
            Glide.with(mContext).load(item.getGoods_img()).into((ImageView) helper.getView(R.id.iv_pic));
        }
    }

    private void convertUrl(String discountLink, String goodId) {
        OkHttpUtils.post()
                .url(UrlHost.JD_CONVERT_URL)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("discount_link", discountLink)
                .addParams("goods_id", goodId)
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    JDConvertResponse convertResponse = JsonUtils.parseByGson(response, JDConvertResponse.class);
                    if (convertResponse != null) {
                        if (CallbackCode.SUCCESS.equals(convertResponse.getCode())) {
//                            ToastUtils.showToast(xieYiResponse.getMs());
                            String data = convertResponse.getData();
                            openJD(data);//跳转京东
                        } else {
                            ToastUtils.showToast(convertResponse.getMs());
                        }
                    } else {
                        ToastUtils.showToast("请求失败！");
                    }
                } else {
                }
            }
        });
    }

    private void openJD(String urlStr) {
        KeplerApiManager.getWebViewService().openAppWebViewPage(this,
                urlStr,
                mKeplerAttachParameter,
                openAppAction);
    }

    ///////////////////////////////////////////////////////////////////////////
    // 京东
    ///////////////////////////////////////////////////////////////////////////
    private KeplerAttachParameter mKeplerAttachParameter = new KeplerAttachParameter();
    OpenAppAction openAppAction = new OpenAppAction() {
        @Override
        public void onStatus(final int status, final String url) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(status);
                    switch (status) {
                        case OpenAppAction.OpenAppAction_start://开始状态未必一定执行
                            KLog.e("开始");
                            break;
                        case OpenAppAction.OpenAppAction_result_NoJDAPP:
                            //未安装京东
                            KLog.e("未安装京东");
                            break;
                        case OpenAppAction.OpenAppAction_result_BlackUrl:
                            //不在白名单
                            KLog.e("不在白名单");
                            break;
                        case OpenAppAction.OpenAppAction_result_ErrorScheme:
                            //协议错误
                            KLog.e("协议错误");
                            break;
                        case OpenAppAction.OpenAppAction_result_APP:
                            //呼京东成功
                            KLog.e("呼京东成功");
                            break;
                        case OpenAppAction.OpenAppAction_result_NetError:
                            //网络异常
                            KLog.e("网络异常");
                            break;
                        default:
                            break;
                    }
                }
            });
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case OpenAppAction.OpenAppAction_result_NoJDAPP:
                    //未安装京东
                    ToastUtils.showToast("未安装京东");
                    break;
                case OpenAppAction.OpenAppAction_result_NetError:
                    //网络异常
                    ToastUtils.showToast("网络异常");
                    break;
                default:
                    break;
            }
        }
    };
}
